const { history_list, create_base_rate, service_rate } = require("./data.js");

const current_history_list = history_list.reverse();
let create_list = [];

const handle_have_pre = (pre) => {
  return (
    current_history_list.filter((item) => {
      const itemDate = new Date(item.create_time);

      return itemDate.getTime() == pre.getTime();
    }).length > 0
  );
};

// 取出近一个月数据
const filter_month = (today) => {
  let filteredData = [];
  // 今天建仓，看的是前一个月的数据，不包含今天
  const current = new Date(today);

  const pre = new Date(today);
  pre.setDate(current.getDate() - 30);

  if (handle_have_pre(pre)) {
    filteredData = current_history_list.filter((item) => {
      const itemDate = new Date(item.create_time);
      return itemDate < current && itemDate >= pre;
    });
  }

  return filteredData;
};

// 计算近一个月数据（收益、高值、低值）
const get_month_data = (list) => {
  // 以第一日为基础，计算所有幅度
  const rate_list = list.map((item) => {
    const base_value = list[0].value;
    return {
      ...item,
      rate: ((item.value / base_value - 1) * 100).toFixed(2),
    };
  });

  const month_rate_list = rate_list.map((item) => item.rate);
  const month_max_rate = Math.max(...month_rate_list);
  const month_min_rate = Math.min(...month_rate_list);
  const month_rate = rate_list.at(-1)?.rate;
  const range = rate_list.at(-1)?.value;
  const last_10 = rate_list
    .slice(-10)
    .reverse()
    .map(({ create_time, rate, range }) => ({ create_time, range, rate }));
  const create_time = list.at(-1)?.create_time;

  return {
    create_time,
    range,
    month_rate,
    month_max_rate,
    month_min_rate,
    last_10,
  };
};

// 找到合适的点
const find_create_point = () => {
  current_history_list.forEach((item, index) => {
    let month_list = filter_month(item.create_time);

    if (month_list.length > 0) {
      const obj = get_month_data(month_list);

      if (obj.month_rate == create_base_rate) {
        create_list = obj;
        console.log("obj", obj);
      }
    }
  });
  return create_list;
};

// 根据当天得出近一月高值和低值,以便确认n
const find_data_by_time = (create_time) => {
  const create_list = [];
  let month_list = filter_month(create_time);

  if (month_list.length > 0) {
    const obj = get_month_data(month_list);
    // console.log("obj", obj);

    if (obj.month_rate == create_base_rate) {
      create_list = obj;
    }
  }
  return create_list;
};

// find_data_by_time('2024-06-06')
// find_create_point();

module.exports = {
  find_create_point,
  find_data_by_time,
};
